<template>
  <a-modal
    class="table-select-modal-wrapper"
    :title="title"
    :width="width"
    :visible="visible"
    :maskClosable="false"
    @ok="onSubmit"
    @cancel="onCancel"
  >
    <a-row>
      <a-col :span="18" style="padding: 24px; border-right: 1px solid #e8e8e8;">
        <a-input-search
          v-if="!customizeQuery"
          style="width: 300px;"
          :placeholder="this.searchPlaceholder"
          allowClear
          v-model="searchKey"
          @search="onSearch"
        />
        <slot name="customizeQuery" v-else></slot>
        <s-table
          style="margin-top: 16px;"
          ref="table"
          :rowKey="rowKey"
          :columns="columns"
          :data="loadData"
          :filterMultiple="multi"
          :rowSelection="rowSelection"
          :showPagination="showPagination"
        />
      </a-col>
      <a-col :span="6">
        <div class="sub-title">{{ $t('common.selectedItems') }}</div>
        <ul class="selected-list">
          <li class="selected-item" v-for="item in selectedItems" :key="item[rowKey]">
            <span class="selected-item-name" :title="renderSelectedItem(item)">{{ renderSelectedItem(item) }}</span>
            <a href="javascript:;" @click="onDeleteItem(item[rowKey])">
              <a-icon type="close-circle" />
            </a>
          </li>
        </ul>
      </a-col>
    </a-row>
  </a-modal>
</template>

<script>
import { STable } from '@/components'
import { i18nRender } from '@/locales'

export default {
  name: 'TableSelectModal',
  components: {
    STable
  },
  props: {
    columns: {
      type: Array,
      required: true
    },
    customizeQuery: {
      type: Boolean,
      required: false,
      default: false
    },

    data: {
      type: Function,
      required: true
    },

    // 默认选中的项目。不用defaultSelectedKeys的原因：分页加载的数据中如果不包含key，则无法渲染右侧已选中列表
    defaultSelectedItems: {
      type: Array,
      default: () => []
    },

    // 查询条件未填写时，表格里是否展示所有数据/不展示数据
    defaultShowAll: {
      type: Boolean,
      default: false
    },

    // 不让选择的项目的key
    disabledSelectedKeys: {
      type: Array,
      default: () => []
    },

    extraQueryParams: {
      type: Object,
      default: () => ({})
    },

    // 是否可以多选
    multi: {
      type: Boolean,
      default: false
    },

    rowKey: {
      type: String,
      default: 'id'
    },

    // record无法被选中的前提条件。eg：若该属性值为 {key: 'field1', value: 'val'} 时，当record满足record[field1] === 'val' 则record无法被选中
    rowSelectionDisabledFlag: {
      type: Object | null,
      default: null
    },

    searchField: {
      type: String,
      default: 'searchField'
    },

    searchPlaceholder: {
      type: String,
      default: () => i18nRender('common.plzInput')
    },

    // 需要展现在已选列表的字段，即columns里的dataIndex，展现形式为：[field0]field1_field2_field3_ ....
    showItemFields: {
      type: Array,
      required: true
    },

    showPagination: {
      type: Boolean,
      default: false
    },

    title: {
      type: String,
      default: ''
    },

    visible: {
      type: Boolean,
      default: false
    },

    width: {
      type: Number,
      default: 1024
    }
  },
  data () {
    return {
      searchKey: '',
      selectedRowKeys: [],
      selectedItems: [],
      customizeQueryParams: {},
      loadData: params => {
        let queryParams = this.showPagination
          ? { [this.searchField]: this.searchKey, ...params, ...this.extraQueryParams }
          : { [this.searchField]: this.searchKey, ...this.extraQueryParams }
        if (this.customizeQuery) {
          delete queryParams[this.searchField]
          queryParams = { ...queryParams, ...this.customizeQueryParams }
        }
        return this.data(queryParams).then(res => {
          if (!res.data.data) {
            res.data.data = []
          }
          return this.showPagination
            ? res.data
            : {
              data: res.data
            }
        })
      }
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange,
        type: this.multi ? 'checkbox' : 'radio',
        getCheckboxProps: record => ({
          props: {
            disabled:
              this.disabledSelectedKeys.includes(record[this.rowKey]) ||
              (!!this.rowSelectionDisabledFlag &&
                record[this.rowSelectionDisabledFlag.key] === this.rowSelectionDisabledFlag.value)
          }
        })
      }
    }
  },
  watch: {
    visible (val) {
      if (val) {
        const table = this.$refs.table
        !!table && table.refresh(true)
        this.selectedRowKeys = this.defaultSelectedItems.map(ele => ele[this.rowKey])
        this.selectedItems = this.defaultSelectedItems
      }
    }
  },
  created () {},
  methods: {
    onSearch () {
      this.$refs.table.refresh(true)
    },
    onCustomizeQuery (customizeQueryParams) {
      this.customizeQueryParams = customizeQueryParams
      this.$refs.table.refresh(true)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      const arr = []
      const Obj = {};
      [...this.selectedItems, ...selectedRows].forEach(i => {
        if (!Obj[`${i[this.rowKey]}`] && this.selectedRowKeys.includes(i[this.rowKey])) {
          arr.push(i)
          Obj[`${i[this.rowKey]}`] = true
        }
      })
      this.selectedItems = arr
    },

    renderSelectedItem (item) {
      const fields = this.showItemFields
      if (fields.length < 1) {
        return ''
      }
      let itemStr = ''
      for (let i = 0; i < fields.length; i++) {
        const field = fields[i]
        if (i === 0) {
          itemStr += `[${item[field]}]`
        } else if (i === 1) {
          itemStr += item[field]
        } else {
          // if (item[field]) {
          //   itemStr += `_${item[field]}`
          // }
        }
      }
      return itemStr
    },

    onDeleteItem (id) {
      this.selectedRowKeys = this.selectedRowKeys.filter(ele => ele !== id)
      this.selectedItems = this.selectedItems.filter(ele => ele[this.rowKey] !== id)
    },

    onSubmit () {
      this.$emit('submit', this.selectedItems)
      this.reset()
    },

    onCancel () {
      this.$emit('cancel')
      this.reset()
    },

    reset () {
      this.searchKey = ''
      this.customizeQueryParams = {}
      this.selectedRowKeys = []
      this.selectedItems = []
    }
  }
}
</script>

<style lang="less">
.table-select-modal-wrapper {
  .ant-modal-body {
    padding: 0;

    .sub-title {
      font-weight: bold;
      font-size: 14px;
      color: #000;
      line-height: 32px;
      padding-left: 8px;
    }

    .selected-list {
      padding: 0 16px;
      list-style-type: none;
      .selected-item {
        margin: 2px 0;
        display: flex;
        justify-content: space-between;
        width: 100%;
        align-items: center;
        .selected-item-name {
          display: block;
          // word-break: break-all;
          width: 100%;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
